package banks;

import database.DatabaseManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Random;

/**
 * the capital market control class  manages all banks
 * @author Mike
 */
public class CapitalMarketControl {
    private static CapitalMarketControl instance = null;
    private Hashtable<String,Bank> banks;
    private Random rand;

    private CapitalMarketControl () throws SQLException {
        banks = new Hashtable<String, Bank>();
        rand = new Random();
        ResultSet rs = DatabaseManager.getInstance().query("SELECT * FROM Bank");
        while (rs.next()) {
            String name = rs.getString("Name");
            banks.put(name, new Bank(rs.getInt("ID"),name));
        }
       
    }
    /**
     * returns the instance of the capital market controll class
     * @return
     */
    public static CapitalMarketControl getInstance() throws SQLException {
        if (instance == null) {
            instance = new CapitalMarketControl();
        }
        return instance;
    }
    /**
     * this methode will create a new account, it is not possible to instanciate a bank directly
     * this factory methode has to be used
     * @param name
     * @return the instance of the new bank
     */
    public Bank bringNewBankOnMarket(int id,String name) throws SQLException {
        if (banks.get(name) == null) {
            DatabaseManager.getInstance().update("INSERT INTO Bank VALUES ("+id+",'"+name+"')");
            Bank bank = new Bank(id,name);
            banks.put(name, bank);
            return bank;
        }
        else {
            throw new IllegalArgumentException();
        }
    }
    /**
     * will return a instance of the bank specified by it's name, see multion pattern
     * @param name the name of the bank
     * @return the instance of the bank
     */
    public Bank getBankByName(String name) {
        if (banks.get(name) != null) {
            return banks.get(name);
        }
        else {
            throw new IllegalArgumentException();
        }
    }
    /**
     * this methode will return a random instance of a bank
     * @return a instance of a bank
     */
    public Bank getRandomBank() {
        if (banks.isEmpty()) {
            throw new IllegalArgumentException();
        }
        else {
            int stepover = rand.nextInt(banks.size());
            Iterator<Bank> it = banks.values().iterator();
            Bank bank = it.next();
            while(stepover > 0){
                stepover--;
                bank = it.next();
            }
            return bank;
        }
    }
}
